package com.moss.cloud.common.security.condition;

import com.alibaba.fastjson2.JSONObject;
import com.moss.cloud.common.core.constant.ServiceList;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.jetbrains.annotations.NotNull;
import org.springframework.context.annotation.Condition;
import org.springframework.context.annotation.ConditionContext;
import org.springframework.core.io.Resource;
import org.springframework.core.type.AnnotatedTypeMetadata;
import org.yaml.snakeyaml.Yaml;
import java.io.InputStream;
import java.util.Map;
@Slf4j
public class CustomCondition implements Condition {
    private static final String SPRING = "spring";
    private static final String APPLICATION = "application";
    private static final String NAME = "name";
    @SneakyThrows
    @Override
    public boolean matches(ConditionContext context, @NotNull AnnotatedTypeMetadata metadata) {
        Resource resource = context.getResourceLoader().getResource("classpath:bootstrap.yml");
        if(resource.exists()){
            InputStream inputStream = resource.getInputStream();
            Yaml yaml = new Yaml();
            Map<String, Object> yamlMap = yaml.load(inputStream);
            Object object = yamlMap.get(SPRING);
            JSONObject jsonObject = JSONObject.parseObject(JSONObject.toJSONString(object)).getJSONObject(APPLICATION);
            String appName = jsonObject.getString(NAME);
            return !appName.equals(ServiceList.MOSS_CLOUD_AUTH);
        }else {
            log.info("未找到bootstrap.yml配置文件，请使用标准微服务配置，否则将失去动态注册bean功能");
        }
        return Boolean.TRUE;
    }
}
